package com.anolesoft.yr.mbus.contm.ctrl;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.anolesoft.common.core.web.domain.AjaxResult;
import com.anolesoft.common.core.web.page.TableDataInfo;
import com.anolesoft.yr.mbus.cont.entity.ContType;
import com.anolesoft.yr.mbus.cont.entity.ItemType;
import com.anolesoft.yr.mbus.cont.entity.PageType;
import com.anolesoft.yr.mbus.cont.service.ContTypeService;
import com.anolesoft.yr.mbus.contm.dto.ContmBaseClauseDto;
import com.anolesoft.yr.mbus.contm.dto.ContmBaseMainDto;
import com.anolesoft.yr.mbus.contm.entity.ContmBaseClause;
import com.anolesoft.yr.mbus.contm.entity.ContmBaseClauseExample;
import com.anolesoft.yr.mbus.contm.entity.ContmBaseMain;
import com.anolesoft.yr.mbus.contm.entity.ContmBaseMainExample;
import com.anolesoft.yr.mbus.contm.service.ContmBaseClauseService;
import com.anolesoft.yr.mbus.contm.service.ContmBaseMainService;
import com.anolesoft.yr.store.stk.util.StringUtil;
import com.anolesoft.yr.util.SecurityUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;

import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;


@AllArgsConstructor
@RestController
@RequestMapping("/contm/contm_base_main")
public class ContmBaseMainController {


    private ContmBaseMainService contmBaseMainService;
    private ContmBaseClauseService contmBaseClauseService;
    private ContTypeService contTypeService;
    @RequestMapping(value = "/get", produces = {"application/json;charset=UTF-8"})
    public AjaxResult get(ContmBaseMain contmBaseMain) {
        Page<ContmBaseMain> page = new Page<>(contmBaseMain.getPage(), contmBaseMain.getRows());
        String contType = StrUtil.nullToEmpty(contmBaseMain.getContType());
        LambdaQueryWrapper<ContmBaseMain> like = new QueryWrapper<ContmBaseMain>()
                .lambda()
                .like(ContmBaseMain::getContType, contType)
                .orderByDesc(ContmBaseMain::getCTime);

        List<ContmBaseMain> contmBaseMains = contmBaseMainService.selectAll(page, like);
        return AjaxResult.success(new TableDataInfo(page.getTotal(), contmBaseMains));
    }

    @RequestMapping(value = "/del", produces = {"application/json;charset=UTF-8"})
    public AjaxResult del(@RequestBody ContmBaseMain contmBaseMain) {
        contmBaseMainService.removeById(contmBaseMain.getObjuid());

        return AjaxResult.success("删除成功");
    }

    @RequestMapping(value = "/delbatch", produces = {"application/json;charset=UTF-8"})
    public AjaxResult delbatch(@RequestBody List<ContmBaseMain> contmBaseMains) {
        List<String> collect = contmBaseMains.stream().map(ContmBaseMain::getObjuid).collect(Collectors.toList());
        contmBaseMainService.removeByIds(collect);
        return AjaxResult.success("删除成功");
    }

    @RequestMapping(value = "/add", produces = {"application/json;charset=UTF-8"})
    public AjaxResult add(@RequestBody ContmBaseMainDto contmBaseMainDto){
        String username = SecurityUtils.getLoginUser().getEmpUid();
        String objuid = StringUtil.generateRundom32String();
        ContmBaseMain contmBaseMain = ContmBaseMain.builder().cUserUid(username).contType(contmBaseMainDto.getContType()).cTime(new Date()).remark(contmBaseMainDto.getRemark()).objuid(objuid).build();
        List<ContmBaseClauseDto> contmBaseClauseDtos = contmBaseMainDto.getContmBaseClauseDtos();
        List<ContmBaseClause> contmBaseClauses = Lists.newArrayList();
        for (int i = 0; i < contmBaseClauseDtos.size(); i++) {
            ContmBaseClauseDto contmBaseClauseDto = contmBaseClauseDtos.get(i);
            contmBaseClauses.addAll(contmBaseClauseDto.toContmBaseClauses(objuid));
        }
        for (int i = 0; i < contmBaseClauses.size(); i++) {
            contmBaseClauses.get(i).setParentUid("");
            contmBaseClauses.get(i).setOrderCode(Byte.parseByte(Integer.toString(i)));
        }
        contmBaseClauseService.pageInsertBatch(contmBaseClauses);
        contmBaseMainService.save(contmBaseMain);
        return AjaxResult.success("成功");
    }

    @RequestMapping(value = "/getForEdit", produces = {"application/json;charset=UTF-8"})
    public AjaxResult getForEdit(ContmBaseMain contmBaseMain){
        ContmBaseClauseExample contmBaseClauseExample = new ContmBaseClauseExample();
        contmBaseClauseExample.setOrderByClause("order_code");
        contmBaseClauseExample.createCriteria().andContBaseMainUidEqualTo(contmBaseMain.getObjuid());
        List<ContmBaseClause> contmBaseClauses = contmBaseClauseService.selectByExample(contmBaseClauseExample);
        List<ContmBaseClauseDto> contmBaseClauseDtos = contmBaseClauses.stream().map(a -> a.toContmBaseClauseDto()).collect(Collectors.toList());
        for (int i = 0; i < contmBaseClauseDtos.size(); i++) {
            if (contmBaseClauseDtos.get(i).getType().equals("nr")){
                for (int j = 0; j < contmBaseClauseDtos.size() ; j++) {
                    if (contmBaseClauseDtos.get(j).getId().equals(contmBaseClauseDtos.get(i).getPId())){
                        contmBaseClauseDtos.get(j).setContent(contmBaseClauseDtos.get(i).getTitle());
                    }
                }
            }
        }
        contmBaseClauseDtos=contmBaseClauseDtos.stream().filter(a->a.getType().equals("bt")).collect(Collectors.toList());
        List<String> titles = Lists.newArrayList(PageType.FIRST_PAGE,PageType.SECOND_PAGE,PageType.MAKE_PAGE,PageType.CONTENT_PAGE,PageType.SIGN_PAGE,PageType.LAST_PAGE);
        List <ContmBaseClauseDto>titleDto = Lists.newArrayList();

        for (int i = 0; i < titles.size(); i++) {
            titleDto.add(ContmBaseClauseDto.builder().id(Integer.toString(i)).name(titles.get(i)).pId("").ppId("").build());
        }
        Map<String, String> parentMap = titleDto.stream().collect(Collectors.toMap(ContmBaseClauseDto::getName, ContmBaseClauseDto::getId));
        for (int i = 0; i < contmBaseClauseDtos.size(); i++) {
            ContmBaseClauseDto contmBaseClauseDto = contmBaseClauseDtos.get(i);
            if (contmBaseClauseDto.getPpId() == null ||contmBaseClauseDto.getPpId().equals("")){
                contmBaseClauseDto.setPId(parentMap.get(contmBaseClauseDto.getPageType()));
                contmBaseClauseDto.setPpId(parentMap.get(contmBaseClauseDto.getPageType()));
            }
        }
        contmBaseClauseDtos.addAll(titleDto);
        return AjaxResult.success(contmBaseClauseDtos);
    }
    @RequestMapping(value = "/editExecute", produces = {"application/json;charset=UTF-8"})
    public AjaxResult editExecute(@RequestBody ContmBaseMainDto contmBaseMainDto){
        String username = SecurityUtils.getLoginUser().getEmpUid();
        String objuid = contmBaseMainDto.getObjuid();
        System.out.println(contmBaseMainDto.toString());
        ContmBaseMain contmBaseMain = ContmBaseMain.builder().cUserUid(username).contType(contmBaseMainDto.getContType()).cTime(new Date()).remark(contmBaseMainDto.getRemark()).objuid(objuid).build();
        ContmBaseClauseExample contmBaseClauseExample = new ContmBaseClauseExample();
        contmBaseClauseExample.createCriteria().andContBaseMainUidEqualTo(objuid);
        contmBaseClauseService.deleteByExample(contmBaseClauseExample);
        ContmBaseMainExample contmBaseMainExample = new ContmBaseMainExample();
        contmBaseMainExample.createCriteria().andObjuidEqualTo(objuid);
        contmBaseMainService.updateByExampleSelective(contmBaseMain,contmBaseMainExample);
        List<ContmBaseClauseDto> contmBaseClauseDtos = contmBaseMainDto.getContmBaseClauseDtos();
        List<ContmBaseClause> contmBaseClauses = Lists.newArrayList();
        for (int i = 0; i < contmBaseClauseDtos.size(); i++) {
            ContmBaseClauseDto contmBaseClauseDto = contmBaseClauseDtos.get(i);
            contmBaseClauses.addAll(contmBaseClauseDto.toContmBaseClauses(objuid));
        }

        for (int i = 0; i < contmBaseClauses.size(); i++) {
            contmBaseClauses.get(i).setParentUid("");
            contmBaseClauses.get(i).setOrderCode(Byte.parseByte(Integer.toString(i)));
        }
        contmBaseClauseService.pageInsertBatch(contmBaseClauses);
        return AjaxResult.success("修改成功");
    }

    @RequestMapping(value = "/getForUse", produces = {"application/json;charset=UTF-8"})
    public AjaxResult getForUse(ContmBaseMain contmBaseMain) {


        ContType contType = contTypeService.getById(contmBaseMain.getContType());

        ContmBaseMainExample contmBaseMainExample = new ContmBaseMainExample();
        contmBaseMainExample.createCriteria().andContTypeEqualTo(contType.getName());
        List<ContmBaseMain> contmBaseMains = contmBaseMainService.selectByExample(contmBaseMainExample);

        if (contmBaseMains != null && !contmBaseMains.isEmpty()) {
            String objuid = contmBaseMains.get(0).getObjuid();
            ContmBaseClauseExample contmBaseClauseExample = new ContmBaseClauseExample();
            contmBaseClauseExample.setOrderByClause("order_code");
            contmBaseClauseExample.createCriteria().andContBaseMainUidEqualTo(objuid);
            List<ContmBaseClause> contmBaseClauses = contmBaseClauseService.selectByExample(contmBaseClauseExample);
            List<ContmBaseClauseDto> contmBaseClauseDtos = contmBaseClauses.stream().map(a -> a.toContmBaseClauseDto()).collect(Collectors.toList());
            for (int i = 0; i < contmBaseClauseDtos.size(); i++) {
                if (contmBaseClauseDtos.get(i).getType().equals(ItemType.CONTENT)) {
                    for (int j = 0; j < contmBaseClauseDtos.size(); j++) {
                        if (contmBaseClauseDtos.get(j).getId().equals(contmBaseClauseDtos.get(i).getPId())) {
                            contmBaseClauseDtos.get(j).setContent(contmBaseClauseDtos.get(i).getTitle());
                        }
                    }
                }
            }
            contmBaseClauseDtos = contmBaseClauseDtos.stream().filter(a -> a.getType().equals(ItemType.TITLE)).collect(Collectors.toList());
            List<String> titles = Lists.newArrayList(PageType.FIRST_PAGE,PageType.SECOND_PAGE,PageType.MAKE_PAGE,PageType.CONTENT_PAGE,PageType.SIGN_PAGE,PageType.LAST_PAGE);
            List<ContmBaseClauseDto> titleDto = Lists.newArrayList();

            for (int i = 0; i < titles.size(); i++) {
                titleDto.add(ContmBaseClauseDto.builder().id(Integer.toString(i)).name(titles.get(i)).pId("").ppId("").build());
            }
            Map<String, String> parentMap = titleDto.stream().collect(Collectors.toMap(ContmBaseClauseDto::getName, ContmBaseClauseDto::getId));
            for (int i = 0; i < contmBaseClauseDtos.size(); i++) {
                ContmBaseClauseDto contmBaseClauseDto = contmBaseClauseDtos.get(i);
                if (contmBaseClauseDto.getPpId() == null || contmBaseClauseDto.getPpId().equals("")) {
                    contmBaseClauseDto.setPId(parentMap.get(contmBaseClauseDto.getPageType()));
                    contmBaseClauseDto.setPpId(parentMap.get(contmBaseClauseDto.getPageType()));
                }
            }
            contmBaseClauseDtos.addAll(titleDto);
            return AjaxResult.success(contmBaseClauseDtos);
        }else{
            return AjaxResult.success();
        }

    }



}
